package com.slj.cloudaibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.slj.cloudaibaba.client.PayClient;
import com.slj.cloudaibaba.entity.OrderEntity;
import com.slj.cloudaibaba.model.response.Result;
import com.slj.cloudaibaba.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RefreshScope
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Value("${common.name}")
    private String userName;

    @Autowired
    private PayClient payClient;

    @GetMapping("/port")
    public String port() {
        return orderService.getPort();
    }

    /**
     * 配置中心测试
     *
     * @return
     */
    @GetMapping("/nacos/config")
    public String nacosConfig() {
        return userName;
    }

    /**
     * 流控测试
     *
     * @return
     */
    @GetMapping("/flow/limit")
    public String flowLimit() {
        return "flow...limit...";
    }

    /**
     * 熔断测试
     *
     * @return
     */
    @GetMapping("/circuit")
    public String circuit() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "circuit..breaker...";
    }


    @GetMapping("/resource/{id}")
    @SentinelResource(value = "sentinelResource", blockHandler = "blockHandler", fallback = "fallback")
    public String resource(@PathVariable("id") Integer id) {
        if (id.equals(1)) {
            throw new RuntimeException("error");
        }
        return "sentinelResource";
    }

    @GetMapping("/pay/{id}")
    public Result<String> pay(@PathVariable("id") Integer id) {
        return payClient.getPort(id);
    }

    public String blockHandler(@PathVariable("id") Integer id, BlockException e) {
        log.info("=============================");
        log.error(e.getMessage());
        return "=========blockHandler==========";
    }

    public String fallback(@PathVariable("id") Integer id, Throwable e) {
        log.info("++++++++++++++++++++++++++++++");
        log.error(e.getMessage());
        return "+++++++++++++fallback+++++++++++++++++";
    }

    @PostMapping("")
    public Result<Void> save(@RequestBody OrderEntity orderEntity) {
        orderService.insert(orderEntity);
        return Result.success(null);
    }

    @GetMapping("")
    public Result<List<OrderEntity>> findAll() {
        return Result.success(orderService.findAll());
    }
}
